package LeetCode.exercise;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class LC30 {
    public static void main(String[] args) {
        LC30 l = new LC30();
        System.out.println(l.findSubstring("wordgoodgoodgoodbestword", new String[]{ "word","good","best","word"}));
    }
    public List<Integer> findSubstring(String s, String[] words) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        for(String str : words){
            hashMap.put(str, hashMap.getOrDefault(str, 0) + 1);
        }
        int len = words[0].length();
        for(int i = 0; i < len; i++){
            HashMap<String, Integer> hashMap2 = new HashMap<>();
            for(int left = i, right = i, count = 0; right + len <= s.length(); right += len){
                String in = s.substring(right, right+len);
                hashMap2.put(in, hashMap2.getOrDefault(in, 0) + 1);
                if(hashMap2.get(in) <= hashMap.getOrDefault(in, 0)){
                    count++;
                }
                if(right - left + 1 > words.length * len){
                    String out = s.substring(left, left+len);
                    if(hashMap2.get(out) <= hashMap.getOrDefault(out, 0)){
                        count--;
                    }
                    hashMap2.put(out, hashMap2.get(out) - 1);
                    left += len;
                }
                if(count == hashMap.size()){
                    list.add(left);
                }
                if(count == words.length){
                    list2.add(left);
                }
            }
        }
        return list;
    }
}
